package pri.zey.custom.tools;/**
 * Created by Administrator on 2016/3/16.
 */

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>类描述
 * 时间工具
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>属性描述
 * >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>方法描述
 * getDateTime(Date d)---->获取时间dateTime，格式：yyyy-MM-dd HH:mm:ss
 * getNowDateTime()---->获取当前时间dateTime，格式：yyyy-MM-dd HH:mm:ss
 * getDate(Date d)---->获取时间date，格式：yyyy-MM-dd
 * getNowDate()---->获取当前时间dateTime，格式：yyyy-MM-dd
 * getTime(Date d)---->获取时间time,格式如： HH:mm:ss
 * getNowTime()---->获取当前时间time,格式如： HH:mm:ss
 * convertDateTimeToString(String target_format, Date datetime)---->用指定的日期格式把Date类型转换为String类型
 * getCNToday()---->取得当前时间,格式如：2007年8月23日
 * getTimestamp(String strDate)---->字符串转换成 Timestamp
 * dateCompare()---->比较当前日期和指定日期 return boolean 如果当前日期在指定日期之前返回true否则返回flase
 * now()---->时间戳转格式时间（1357872222598 转 2013-01-11 10:43:42.598）
 * getTimestamp(Date d)---->获取时间戳
 * getLastMonth(String curmonth)---->取的当前月的上一个月
 * getNextMonth(String curmonth)---->取的当前月的下一个月
 * daysBetweenDates(Date startDate, Date endDate)---->得到两个日期之间相差的天数
 * getDateOffset(Date date, int type, int how)---->取得基础日期date按一定标准偏移后的日期
 * str8to10(String date)---->格式转换（20060506 -> 2006-05-06）
 * str10to8(String date)---->格式转换（2006-05-06 -> 20060506）
 * str6to8(String date)---->格式转换（163012 -> 16:30:12）
 * str8to6(String date)---->格式转换（16:30:12 -> 163012）
 * dispersionMonth(String strDate1, String strDate2)---->得到两个日期之间相差的天数
 * getMonthFirstDay()---->得到本月的第一天
 * getMonthLastDay()---->得到本月的最后一天
 * getMonthLastDay()---->获取指定日期所在月份的最后一天
 * getCustomerDay(int date)---->得到自定义日期
 * getPreCustomerDay(int date)---->得到自定义日期前一天日期
 * getNextCustomerDay(int date)---->得到自定义日期后一天日期
 * timeMillisToNormalTime(long ms)---->将毫秒数换算成x天x时x分x秒x毫秒
 * getTimeStamp()---->获取当前时间戳
 */
public class Tdate {

    private final String YMD = "yyyy-MM-dd";
    private final String YMDH = "yyyy-MM-dd HH";
    private final String YMDHM = "yyyy-MM-dd HH:mm";
    private final String YMDHMS = "yyyy-MM-dd HH:mm:ss";
    private final String H = "HH";
    private final String HM = "HH:mm";
    private final String HMS = "HH:mm:ss";

    /**
     * 获取当前时间戳
     * @return
     */
    public static String getTimeStamp(){
        return String.valueOf(System.currentTimeMillis());
    }

    /**
     * 获取时间dateTime，格式：yyyy-MM-dd HH:mm:ss
     *
     * @param d
     * @return 返回格式如： yyyy-MM-dd HH:mm:ss 的字符串
     */
    public String getDateTime(Date d) {
        if (d == null) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat(YMDHMS);
        return format.format(d);
    }

    /**
     * 获取当前时间dateTime，格式：yyyy-MM-dd HH:mm:ss
     * @return
     */
    public String getNowDateTime() {
        return getDateTime(new Date());
    }

    /**
     * 获取时间date，格式：yyyy-MM-dd
     *
     * @param d
     * @return 返回格式如： yyyy-MM-dd 的字符串
     */
    public String getDate(Date d) {
        if (d == null) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat(YMD);
        return format.format(d);
    }

    public String getNowDate() {
        SimpleDateFormat format = new SimpleDateFormat(YMD);
        return format.format(new Date());
    }

    /**
     * 获取时间time,格式如： HH:mm:ss
     *
     * @param d
     * @return 返回格式如： HH:mm:ss 的字符串
     */
    public String getTime(Date d) {
        if (d == null) {
            return "";
        }
        SimpleDateFormat format = new SimpleDateFormat(HMS);
        return format.format(d);
    }

    /**
     * 用指定的日期格式把Date类型转换为String类型
     *
     * @param target_format
     *            日期格式匹配模式
     * @param datetime
     * @return
     */
    public String convertDateTimeToString(String target_format, Date datetime) {
        SimpleDateFormat sdf = new SimpleDateFormat(target_format);
        return sdf.format(datetime);
    }

    /**
     * 取得当前时间
     *
     * @return 当前时间返回的格式 返回：2007年8月23日
     */
    public String getCNToday() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        String currentDateTime = df.format(new Date());
        return currentDateTime.substring(0, 4) + "年" + currentDateTime.substring(5, 7) + "月"
                + currentDateTime.substring(8) + "日";
    }

    /**
     * 字符串转换成 Timestamp
     *
     * @param strDate
     *            2006-08-08 12:12:12.0
     * @return Date
     */
    public Timestamp getTimestamp(String strDate) {
        if (strDate == null) {
            return null;
        }
        Timestamp timestamp = null;
        String val = "";

        if (strDate.length() > 0) {
            if (strDate.length() == 10) {
                val = strDate + " 00:00:00";
            } else if (strDate.contains(".0")) {
                val = strDate.substring(0, strDate.length() - 2);
            }
            timestamp = Timestamp.valueOf(val);
        }
        return timestamp;
    }

    /**
     * 比较当前日期和指定日期 return boolean 如果当前日期在指定日期之前返回true否则返回flase
     *
     * @param str
     *            String
     * @return boolean
     */
    public boolean dateCompare(String str) {
        boolean bea = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String isDate = sdf.format(new Date());
        Date date1;
        Date date0;
        try {
            date1 = sdf.parse(str);
            date0 = sdf.parse(isDate);
            if (date0.after(date1)) {
                bea = true;
            }
        } catch (ParseException e) {
            bea = false;
        }
        return bea;
    }

    /**
     * 时间戳转格式时间（1357872222598 转 2013-01-11 10:43:42.598）
     * @return Timestamp
     */
    public Timestamp now() {
        Date now = new Date();
        return new Timestamp(now.getTime());
    }

    /**
     * 获取时间戳
     * @param date
     * @return Timestamp
     */
    public Timestamp getTimestamp(Date date) {
        return new Timestamp(date.getTime());
    }

    /**
     * 取的当前月的上一个月
     *
     * @param curmonth
     *            200608
     * @return 200607
     */
    public String getLastMonth(String curmonth) {
        String month = curmonth.substring(curmonth.length() - 2);
        String year = curmonth.substring(0, 4);
        int temp = new Integer(month) - 1;
        if (temp == 0) {
            month = "12";
            year = (new Integer(year) - 1) + "";
        } else {
            month = this.leadZeros(temp + "", 2);
        }
        String lastMonth = year + curmonth.substring(4, curmonth.length() - 2) + month;
        return lastMonth;
    }

    /**
     * 取的当前月的下一个月
     *
     * @param curmonth
     *            200608
     * @return 200607
     */
    public String getNextMonth(String curmonth) {
        String month = curmonth.substring(curmonth.length() - 2);
        String year = curmonth.substring(0, 4);
        int temp = new Integer(month) + 1;
        if (temp == 13) {
            month = "01";
            year = (new Integer(year) + 1) + "";
        } else {
            month = this.leadZeros(temp + "", 2);
        }
        String nextMonth = year + curmonth.substring(4, curmonth.length() - 2) + month;
        return nextMonth;
    }

    /**
     * 得到两个日期之间相差的天数
     *
     * @param startDate
     *            newDate 2006-05-01
     * @param endDate
     *            oldDate 2006-03-01
     * @return n 61
     */
    public int daysBetweenDates(Date startDate, Date endDate) {
        int days = 0;
        Calendar calStart = Calendar.getInstance();
        Calendar calEnd = Calendar.getInstance();
        calStart.setTime(startDate);
        calEnd.setTime(endDate);
        int startday = calStart.get(Calendar.DAY_OF_YEAR);
        int endyear = calEnd.get(Calendar.YEAR);
        int startyear = calStart.get(Calendar.YEAR);
        while (endyear > startyear) {
            calStart.set(Calendar.MONTH, 11);
            calStart.set(Calendar.DATE, 31);
            days = days + calStart.get(Calendar.DAY_OF_YEAR);
            startyear = startyear + 1;
            calStart.set(Calendar.YEAR, startyear);
            // System.out.println("YEAR:"+calo.get(Calendar.YEAR)+"MONTH:"+calo.get(Calendar.MONTH)+"DAY:"+calo.get(Calendar.DATE));
        }
        int endday = calEnd.get(Calendar.DAY_OF_YEAR);
        days = days + endday - startday;
        return days;
    }

    /**
     * 取得基础日期date按一定标准偏移后的日期
     *
     * @param date
     *            基础日期
     * @param type
     *            指定日期偏移的标准类型： year-1, Month-2, week-3, Date-5
     * @param how
     *            在基日期上偏移多少，正数对应后移 负数对应前移
     * @return 偏移后的日期
     */
    public Date getDateOffset(Date date, int type, int how) {
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(type, how);
        return calendar.getTime();
    }

    /**
     * 补0
     *
     * @param str
     *            参数：9
     * @param len
     *            参数：4
     * @return 返回：0009
     */
    public static String leadZeros(String str, int len) {
        if (str == null || str.length() == 0) {
            str = "";
            for (int i = 0; i < len; i++) {
                str += "0";
            }
            return str;
        } else {
            str = str.trim();
            int strLen = str.length();
            for (int i = 0; i < len - strLen; i++) {
                str = "0" + str;
            }
            return str;
        }
    }


    /**
     * 20060506 -> 2006-05-06
     *
     * @param date
     * @return
     */
    public String str8to10(String date) {
        String datetmp = date.substring(0, 4) + "-" + date.substring(4, 6) + "-" + date.substring(6, 8);
        return datetmp;
    }

    /**
     * 2006-05-06 -> 20060506
     *
     * @param date
     * @return
     */
    public String str10to8(String date) {
        String datetmp = date.substring(0, 4) + date.substring(5, 7) + date.substring(8, 10);
        return datetmp;
    }

    /**
     * 163012 -> 16:30:12
     * @param date
     * @return
     */
    public String str6to8(String date) {
        if (null != date) {
            return date.substring(0, 2) + ":" + date.substring(2, 4) + ":" + date.substring(4, 6);
        }
        return "";
    }

    /**
     * 16:30:12 -> 163012
     * @param date
     * @return
     */
    public String str8to6(String date) {
        if (null != date) {
            return date.substring(0, 2) + ":" + date.substring(3, 5) + ":" + date.substring(6, 7);
        }
        return "";
    }

    /**
     * 20070808 -> 20070808000000
     *
     * @param date
     * @return
     */
    public String combineDateTime(String date) {
        String rlt = date;
        if (!Tkit.isBlank(date)) {
            if (date.length() == 14) {
                rlt = date;
            } else if (date.length() == 8) {
                rlt += "000000";
            }
        }
        return rlt;
    }

    /**
     * 得到两个日期之间相差的天数
     *
     * @param strDate1
     *            newDate 2006-05-01
     * @param strDate2
     *            oldDate 2006-03-01
     * @return n 0
     */
    @SuppressWarnings("access")
    public int dispersionMonth(String strDate1, String strDate2) {
        int iMonth = 0;
        try {
            int nYear, nMonth, nDay;
            nYear = Integer.parseInt(strDate1.substring(0, 4));
            nMonth = Integer.parseInt(strDate1.substring(5, 7));
            nDay = Integer.parseInt(strDate1.substring(8));
            Calendar objCalendarDate1 = Calendar.getInstance();
            objCalendarDate1.set(nYear, nMonth, nDay);

            nYear = Integer.parseInt(strDate2.substring(0, 4));
            nMonth = Integer.parseInt(strDate2.substring(5, 7));
            nDay = Integer.parseInt(strDate2.substring(8));
            Calendar objCalendarDate2 = Calendar.getInstance();
            objCalendarDate2.set(nYear, nMonth, nDay);

            if (objCalendarDate2.equals(objCalendarDate1)) {
                return 0;
            }
            if (objCalendarDate2.after(objCalendarDate1)) {// 如果strDate2>strDate1
                if (objCalendarDate2.get(Calendar.YEAR) > objCalendarDate1.get(Calendar.YEAR)) {
                    while (objCalendarDate1.get(Calendar.MONTH) != objCalendarDate2.get(Calendar.MONTH)) {
                        objCalendarDate1.add(objCalendarDate1.MONTH, 1);
                        iMonth++;
                    }
                    if (objCalendarDate2.get(Calendar.DATE) > objCalendarDate1.get(Calendar.DATE)) {
                        iMonth = iMonth + 1;
                    }
                    iMonth = iMonth + (objCalendarDate2.get(Calendar.YEAR) - objCalendarDate1.get(Calendar.YEAR)) * 12;
                } else {
                    while (objCalendarDate1.get(Calendar.MONTH) != objCalendarDate2.get(Calendar.MONTH)) {
                        objCalendarDate1.add(objCalendarDate1.MONTH, 1);
                        iMonth++;
                    }
                    if (objCalendarDate2.get(Calendar.DATE) > objCalendarDate1.get(Calendar.DATE)) {
                        iMonth = iMonth + 1;
                    }
                }
            } else {// 如果strDate1>strDate2
                if (objCalendarDate1.get(Calendar.YEAR) > objCalendarDate2.get(Calendar.YEAR)) {
                    while (objCalendarDate1.get(Calendar.MONTH) != objCalendarDate2.get(Calendar.MONTH)) {
                        objCalendarDate2.add(objCalendarDate2.MONTH, 1);
                        iMonth++;
                    }
                    if (objCalendarDate1.get(Calendar.DATE) > objCalendarDate2.get(Calendar.DATE)) {
                        iMonth = iMonth + 1;
                    }
                    iMonth = iMonth + (objCalendarDate1.get(Calendar.YEAR) - objCalendarDate2.get(Calendar.YEAR)) * 12;
                } else {
                    while (objCalendarDate1.get(Calendar.MONTH) != objCalendarDate2.get(Calendar.MONTH)) {
                        objCalendarDate2.add(objCalendarDate2.MONTH, 1);
                        iMonth++;
                    }
                    if (objCalendarDate1.get(Calendar.DATE) > objCalendarDate2.get(Calendar.DATE)) {
                        iMonth = iMonth + 1;
                    }
                }
                iMonth = iMonth * -1;
            }
        } catch (NumberFormatException e) {
            // e.printStackTrace();
            return 0;
        }
        return iMonth;
    }

    /**
     * 得到本月的第一天
     *
     * @return
     */
    public String getMonthFirstDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMinimum(Calendar.DAY_OF_MONTH));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到本月的最后一天
     *
     * @return
     */
    public String getMonthLastDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 获取指定日期所在月份的最后一天
     *
     * @param theDate
     *            currentDate
     * @return
     */
    public String getMonthLastDay(Date theDate) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(theDate);
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        return df.format(calendar.getTime());
    }

    /**
     * 得到下月的第一天
     *
     * @return
     */
    @SuppressWarnings("access")
    public String getNextMonthFirstDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));
        calendar.add(calendar.DAY_OF_MONTH, 1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到当前日期
     *
     * @return
     */
    public String getCurrentDate() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到当前年份
     *
     * @return
     */
    public String getCurrentYear() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到当前月份
     *
     * @return
     */
    public String getCurrentMonth() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到当天
     *
     * @return
     */
    public String getCurrentDay() {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到当前日期前一天
     *
     * @return
     */
    public String getPreCurrentDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到当前日期后一天
     *
     * @return
     */
    public String getNextCurrentDay() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_MONTH, 1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到自定义日期
     *
     * @param date
     * @return
     */
    public String getCustomerDay(int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, date);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到自定义日期前一天日期
     *
     * @param date
     * @return
     */
    public String getPreCustomerDay(int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, date - 1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 得到自定义日期后一天日期
     *
     * @param date
     * @return
     */
    public String getNextCustomerDay(int date) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, date + 1);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        return dateFormat.format(calendar.getTime());
    }

    /**
     * 将毫秒数换算成x天x时x分x秒x毫秒
     *
     * @param ms
     * @return String
     */
    public String timeMillisToNormalTime(long ms) {
        int ss = 1000;
        int mi = ss * 60;
        int hh = mi * 60;
        int dd = hh * 24;

        long day = ms / dd;
        long hour = (ms - day * dd) / hh;
        long minute = (ms - day * dd - hour * hh) / mi;
        long second = (ms - day * dd - hour * hh - minute * mi) / ss;
        long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;

        String strDay = day < 10 ? "0" + day : "" + day;
        String strHour = hour < 10 ? "0" + hour : "" + hour;
        String strMinute = minute < 10 ? "0" + minute : "" + minute;
        String strSecond = second < 10 ? "0" + second : "" + second;
        String strMilliSecond = milliSecond < 10 ? "0" + milliSecond : "" + milliSecond;
        strMilliSecond = milliSecond < 100 ? "0" + strMilliSecond : "" + strMilliSecond;
        return strDay + "天" + strHour + "小时" + strMinute + "分" + strSecond + "秒" + strMilliSecond + "毫秒";
    }

}
